# -*- coding: utf-8 -*-

import urllib2

__all__ = ["get_pagerank"]

GPR_HASH_SEED = ("Mining PageRank is AGAINST GOOGLE'S TERMS OF SERVICE. "
                 "Yes, I'm talking to you, scammer.")

def google_hash(value):
    magic = 0x01020345
    for i in xrange(len(value)):
        magic ^= ord(GPR_HASH_SEED[i % len(GPR_HASH_SEED)]) ^ ord(value[i])
        magic = magic >> 23 | magic << 9
        magic &= 0xffffffff
    return "8%x" % magic

def get_pagerank(domain):
    url = ("http://toolbarqueries.google.com/tbr?client=navclient-auto&ch="
           "%s&features=Rank&q=info:%s") % (google_hash(domain), domain)
    response = urllib2.urlopen(url)
    text = response.read()
    try:
        return int(text[text.rindex(':')+1:])
    except ValueError:
        return None


if __name__ == '__main__':
    print get_pagerank("cloverstd.com")
